package com.onefish.toolkit;

import cn.hutool.core.date.DateUtil;

import java.io.RandomAccessFile;
import java.lang.management.ManagementFactory;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class NioHelper {
    //1、nio文件锁 阻塞锁lock()和非阻塞锁tryLock()，属于进程级别的锁
    //简单来说就是获取不到锁就会一直在这个地方等待，直到获取到才会走下面的部分，线程中断会释放文件锁资源
    public static void main(String[] args) throws Exception {
        String processId = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
        System.out.println(DateUtil.now() + " NioHelper 当前进程id -> " + processId);
        String path = "C:\\Users\\Administrator\\Desktop\\1.txt";
        RandomAccessFile randomAccessFile = new RandomAccessFile(path,"rw");
        FileChannel fileChannel = randomAccessFile.getChannel();
        System.out.println(DateUtil.now() + " NioHelper 开始加锁操作 ... ");
        int size = 3;
        //  区分独占锁[排它锁]和共享锁
//        fileChannel.lock();
//        fileChannel.lock(0, fileChannel.size(),true);
//        FileLock fileLock = fileChannel.tryLock();
        FileLock fileLock = fileChannel.tryLock(0,3,true);
        if (fileLock == null){
            System.out.println(DateUtil.now() + " NioHelper tryLock null");
        }
        System.out.println(DateUtil.now() + " NioHelper 加锁完成！");

        Thread.sleep(Integer.MAX_VALUE);
        randomAccessFile.close();
        fileChannel.close();
    }
}
